package com.springmvc.netty.server.websocket;

import com.alibaba.fastjson.JSON;
import com.springmvc.netty.invote.ActionMapUtil;
import com.springmvc.utils.majiang.Param;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.util.concurrent.GlobalEventExecutor;

public class WebSocketHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {

	public static ChannelGroup channelGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

	@Override
	protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) throws Exception {
		Channel channel = ctx.channel();
		System.out.println(msg.text());

		channel.writeAndFlush(new TextWebSocketFrame("【自己】: " + msg.text() + "\n"));

		Param param = JSON.parseObject(msg.text(), Param.class);
		/* 请求分发 */
		ActionMapUtil.invote(param.getCammand(), ctx, param);

	}

	// 连接建立
	@Override
	public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
		Channel channel = ctx.channel(); // 获取到上线的连接
		channelGroup.writeAndFlush(new TextWebSocketFrame("【服务器】: " + channel.remoteAddress() + "上线\n")); // 服务器发送广播通知
		channelGroup.add(channel); // 将通道添加到组
	}

	// 连接断开
	@Override
	public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
		Channel channel = ctx.channel();
		channelGroup.writeAndFlush(new TextWebSocketFrame("【服务器】: " + channel.remoteAddress() + "下线了\n"));
		channelGroup.remove(channel);
	};

	// 连接激活
	@Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception {
		System.out.println(ctx.channel().remoteAddress() + "上线了");
		//		channelGroup.writeAndFlush(new TextWebSocketFrame("【服务器】: " + ctx.channel().remoteAddress() + "连接激活\n"));
	}

	// 连接断开
	@Override
	public void channelInactive(ChannelHandlerContext ctx) throws Exception {
		System.out.println(ctx.channel().remoteAddress() + "下线了");
		//		channelGroup.writeAndFlush(new TextWebSocketFrame("【服务器】: " + ctx.channel().remoteAddress() + "连接断开\n"));
	};

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
		Channel incoming = ctx.channel();
		System.out.println("Client:" + incoming.remoteAddress() + "异常");
		cause.printStackTrace();
		ctx.close();
	}

}